#define _CRT_SECURE_NO_WARNINGS 1

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */

class Solution {
public:
    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q)
    {
        return _lowestCommonAncestor(root, p, q);
    }

private:
    TreeNode* _lowestCommonAncestor(TreeNode* node, TreeNode* p, TreeNode* q)
    {
        if (node == nullptr)
        {
            return nullptr;
        }

        if (node->val > p->val && node->val > q->val)
        {
            return _lowestCommonAncestor(node->left, p, q);
        }

        if (node->val < p->val && node->val < q->val)
        {
            return _lowestCommonAncestor(node->right, p, q);
        }

        return node;
    }
};